package services.socialuser;

import javax.print.attribute.standard.Finishings;

import models.Activation;
import models.User;
import play.Logger;
import play.libs.Codec;
import securesocial.provider.SocialUser;
import securesocial.provider.UserId;
import securesocial.provider.UserService;
import services.socialuser.util.ModelUserAdaptor;
import services.socialuser.util.SocialUserAdaptor;
import services.socialuser.util.UserAdapter;

public class AnaDIPUserService implements  UserService.Service
{

	@Override
	public SocialUser find(UserId id) 
	{
		Logger.info("AnaDIPUserService.find("+ (id != null?(id.provider + UserAdapter.DELIMITER + id.id):null) + ")");
		
		User findById = User.findById(id.provider + UserAdapter.DELIMITER + id.id);
		ModelUserAdaptor mua = new ModelUserAdaptor(findById);
		
		return mua.getUser();
		
	}

	@Override
	public void save(SocialUser user) 
	{
		Logger.info("AnaDIPUserService.save(" + (user!=null?"user":null) + ")");	
		
		SocialUserAdaptor sua = new SocialUserAdaptor(user);
		User mUser = sua.getUser();
		
		mUser.update();;
		
	}

	@Override
	public String createActivation(SocialUser user) 
	{
		Logger.info("AnaDIPUserService.createActivation(" + (user!=null?"user":null) + ") ");
		
		final String uuid = Codec.UUID();
		SocialUserAdaptor sua = new SocialUserAdaptor(user);
		User mUser = sua.getUser();
		
		Activation activation = new Activation( mUser.stringID, uuid );
		activation.insert();
		
		return uuid;
	}

	@Override
	public boolean activate(String uuid) 
	{	
		Logger.info("AnaDIPUserService.activate(" + uuid + ")");
		
		Activation activation = Activation.findById(uuid);
		User findById = User.findById(activation.userID);
		ModelUserAdaptor mua = new ModelUserAdaptor(findById);
		
		SocialUser user = mua.getUser();
		boolean result = false;

        if( user != null ) 
        {
            user.isEmailVerified =  true;
            save(user);
            activation.delete();
            result = true;
        }
        return result;
	        
		
	}

	@Override
	public void deletePendingActivations() 
	{
		Logger.info("AnaDIPUserService.deletePendingActivations()");
		Activation.deletePendingActivations();
	}
	
}
